<template>
    <van-image
      width="100%"
      height="500px"
      fit="cover"
      :src="product.thumbs_text"
    />

    <div class="detailbox"  
      @touchstart="startTouch" 
      @touchend="endTouch" 
      @touchcancel="endTouch">
      <div class="price">
        <em>￥</em>{{product.price}}<em>起</em>
      </div>
      <h4>{{product.name}}</h4>
    </div>

    <van-popup v-model:show="showPopup" position="bottom">
      <div class="popup-content">
        <van-button plain hairline block primary type="primary" @click="copyText">复制文字</van-button>
        <van-button plain hairline block primary type="primary" @click="copyLink">复制链接</van-button>
      </div>
    </van-popup>
    
    <div class="allkbox"></div>
    
    <!-- 商品规格 -->
    <div class="info_choice">
      <!-- Sku 商品规格 -->
      <div class="commodity" @click="SkuShow = true">
        <div class="opt">
          <div class="title wanl-gray">选择</div>
          <div class="option">
            <div class="selected">
              <div>
                <span>尺码</span>
                <span>颜色</span>
              </div>
            </div>
          </div>
        </div>
        <div class="wanl-gray">
          <img src="/assets/images/go.png" />
        </div>
      </div>
      <!-- 服务 -->
      <div class="commodity" @click="TipShow = true">
        <div class="opt">
          <div class="title wanl-gray">服务</div>
          <div class="option">
            <div class="selected">
              <div>
                <span>7天无理由退款</span>
                <span>·</span>
                <span>24小时内发货</span>
                <span>·</span>
                <span>假一赔十</span>
              </div>
            </div>
          </div>
        </div>
        <div class="wanl-gray">
          <img src="/assets/images/go.png" />
        </div>
      </div>
    </div>

    <div class="allkbox"></div>

    <!-- 选项卡 -->
    <van-tabs v-model:active="TabActive" class="tab" type="card" color="#EE0A24">
      <van-tab title="产品参数">
        <div style="text-align: center;">产品参数描述</div>
      </van-tab>
      <van-tab title="商品评价">
        <div class="rate" style="overflow-x: hidden;">
          <div class="rate-header">
            <div class="rate-score">
              <h4>与描述相符</h4>
              <strong>{{rate}}</strong>
            </div>
            <div class="rate-graph">
              <van-rate v-model="rate" allow-half readonly />
            </div>
          </div>

          <div class="rate-content">
            <div v-if="comment.length > 0">
              <div class="review-box" v-for="(item, key) in comment" :key="key">
                <div class="review-item">
                  <!-- 评论人 -->
                  <div class="from-whom">
                    <div class="avatar">
                      <img :src="item.business.avatar_text" />
                    </div>
                    <div class="name">{{item.business.nickname}}</div>
                  </div>

                  <!-- 评论内容 -->
                  <div class="review-details">
                    <div class="content">{{item.comment}}</div>
                    <!-- <div>
                        <img src="/assets/images/avatar.png" />
                    </div> -->
                    <div class="time">{{item.comtime_text}}</div>
                    <van-rate v-model="item.rate" readonly />
                  </div>
                </div>
              </div>
            </div>
            <div v-else>
              <div class="rate-empty">该商品还没有人写评价呢</div>
            </div>
          </div>
        </div>
      </van-tab>
    </van-tabs>

    <!-- 协议条款 -->
    <van-action-sheet v-model:show="TipShow" title="协议条款">
      <div class="ProductTip">
        三、我们如何使用信息 <br />
        四、我们如何共享信息<br />
        五、我们如何转让信息<br />
        六、我们如何公开披露信息<br />
        七、一般储存期限<br />
        八、我们如何确保您的信息安全<br />
        九、您能做什么<br />
        十、我们如何处理未成年人的个人信息<br />
        十一、您的个人信息的存储地点<br />
        十二、本隐私权政策不适用的范围<br />
        十三、本隐私权政策如何更新<br />
        十四、联系我们<br />
      </div>
    </van-action-sheet>

    <!-- 底部导航栏 -->
    <van-action-bar>
      <van-action-bar-icon icon="chat-o" text="客服" />
      <van-action-bar-icon v-if="product.cart" icon="cart-o" text="购物车" :badge="product.cart" @click="ToCart" />
      <van-action-bar-icon v-else icon="cart-o" text="购物车" @click="ToCart"/>

      <van-action-bar-icon v-if="product.collection" icon="star" text="已收藏" color="#ff5000" @click="collection"/>
      <van-action-bar-icon v-else icon="star-o" text="收藏" @click="collection"/>
      
      <van-action-bar-button type="danger" text="立即购买" @click="SkuShow = true"/>
    </van-action-bar>

    <!-- SKU -->
    <van-sku
      ref="SkuRef"
      v-model="SkuShow"
      :sku="sku"
      :properties="properties"
      :goods="goods"
      :goods-id="product.id"
      @add-cart="AddCart"
      @buy-clicked="Buy"
    />
</template>

<script setup>
  import VanSku from 'vant-sku'
  import 'vant-sku/dist/index.css'
  import { showToast } from 'vant'
  const {proxy} = getCurrentInstance()
  
  let business = proxy.$business
  let proid = proxy.$route.query.proid ? proxy.$route.query.proid : 0
  let product = ref({})
  let comment = ref([])
  //选项卡
  let TabActive = ref(0)
  let rate = ref(0)

  //Sku
  let SkuShow = ref(false)
  let sku = ref({})
  let properties = ref([])
  let goods = ref({})
  let SkuRef = ref({})

  let touchStartTime = null
  const showPopup = ref(false)

  const startTouch = (event) => {
    // 记录触摸开始时间
    touchStartTime = Date.now()
  }

  const endTouch = (event) => {
    // 计算触摸时间
    const touchDuration = Date.now() - touchStartTime

    if (touchDuration >= 1000) {  // 长按超过1秒
      showPopup.value = true
    }
  }

  const copyText = () => {
    const textToCopy = "这是商品的描述文字。"  // 模拟要复制的文字
    navigator.clipboard.writeText(textToCopy)
      .then(() => {
        showPopup.value = false
        showToast("文字已复制到剪贴板！")
      })
      .catch((err) => {
        console.error("复制失败:", err)
      })
  }

  const copyLink = () => {
    const currentUrl = window.location.href  // 获取当前页面的 URL
    navigator.clipboard.writeText(currentUrl)
      .then(() => {
        showPopup.value = false
        showToast("链接已复制到剪贴板！")
      })
      .catch((err) => {
        console.error("复制失败:", err)
      })
  }

  //条款服务
  let TipShow = ref(false)

  // 计算平均分数的函数
  const calculateAverageRate = () => {
    if (comment.value.length === 0) return 0;

    // 将 rate 值相加并除以评论数量
    const totalRate = comment.value.reduce((acc, item) => acc + item.rate, 0);
    return totalRate / comment.value.length;
  };
  
  onMounted(() => {
    productinfo()
  })

  //商品信息
  const productinfo = async () =>
  {
    var params = {
      busid: business.value.id,
      proid
    }

    var result = await proxy.$POST({url: 'product/info', params})

    if(result.codde == 0)
    {
      proxy.$fail({
        message: result.msg,
        duration: 1000,
        onClose: () => proxy.$router.go(-1)
      })
      return false
    }
    product.value = result.data.product
    comment.value = result.data.comment

    comment.value.map((item) => item.rate = parseInt(item.rate))

    rate.value = Number(calculateAverageRate().toFixed(1));

    //sku
    let SkuData = result.data.sku
    let PropertiesData = result.data.properties
    
    goods.value = {picture: product.value.thumbs_text}
    sku.value = SkuData
    properties.value = Object.values(PropertiesData)


  }

  //收藏
  const collection = async () => 
  {
    if(!business.value.id)
    {
      proxy.$fail('请先登录')
      return false
    }

    var params = {
      busid: business.value.id,
      collectid: proid
    }

    var result = await proxy.$POST({url: 'product/collection', params})

    if(result.code == 0)
    {
      proxy.$fail(result.msg)
      return false
    }

    product.value.collection = result.data == 'add' ? true : false
  }

  // 购物车
  const AddCart = async (SkuData) =>
  {
    if(!business.value.id)
    {
      proxy.$fail('请先登录')
      return false
    }

    if(properties.value.length > 0 && !SkuData.selectedSkuComb)
    {
      proxy.$fail('请选择商品规格')
      return false
    }

    //购买数量
    var selectedNum = SkuData.selectedNum

    if(selectedNum <= 0)
    {
      proxy.$fail('购买数量不能小于等于0件')
      return false
    }

    var relationids = []

    //有规格
    if(properties.value.length > 0)
    {
      var SkuProps = SkuData.selectedSkuComb.properties

      for(var item of SkuProps)
      {
        var id = item.v[0] ? item.v[0]['id'] : 0
        if(id) relationids.push(id)
      }
    }

    //组装数据
    var params = {
      busid: proxy.$business.value.id,
      proid: proid,
      nums: selectedNum,
      relationids: relationids.join(','),
    }

    //隐藏弹出框
    SkuShow.value = false

    //发送请求
    var result = await proxy.$POST({
      url: 'cart/add',
      params
    })

    if(result.code == 0)
    {
      proxy.$fail(result.msg)
      return false
    }

    proxy.$success(result.msg)

    //更新购物车数量
    product.value.cart = result.data
  }
  
  //购买
  const Buy = async (SkuData) =>
  {
    // proxy.$router.push({path: '/cart/confirm', query: {pro: checked.value.join(',')}})
    if(!business.value.id)
    {
      proxy.$fail('请先登录')
      return false
    }

    if(properties.value.length > 0 && !SkuData.selectedSkuComb)
    {
      proxy.$fail('请选择商品规格')
      return false
    }

    //购买数量
    var selectedNum = SkuData.selectedNum

    if(selectedNum <= 0)
    {
      proxy.$fail('购买数量不能小于等于0件')
      return false
    }

    var relationids = []

    //有规格
    if(properties.value.length > 0)
    {
      var SkuProps = SkuData.selectedSkuComb.properties

      for(var item of SkuProps)
      {
        var id = item.v[0] ? item.v[0]['id'] : 0
        if(id) relationids.push(id)
      }
    }

    //组装数据
    var params = {
      busid: proxy.$business.value.id,
      proid: proid,
      nums: selectedNum,
      relationids: relationids.join(','),
    }

    console.log(relationids)

    // //隐藏弹出框
    // SkuShow.value = false

    proxy.$router.push({
      path: '/product/confirm', 
      query: {...params}
    })

  }

  const ToCart = async () =>
  {
    proxy.$router.push('/cart')
  }

</script>

<style scoped>
@import url('/assets/css/ProductInfo.css');
</style>